package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
	"go.uber.org/zap"
	"mall-portalv2/global"
	"mall-portalv2/internal/service"
	utils_jwt "mall-portalv2/library/utils.jwt"
	"net/http"
)

/**
* Author: joker
* TODO: test
* Date: 2022/8/25
* Time: 下午5:03
**/

func Jwt(svc *service.Service) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// Bearer ${Token}

		tokentemp := ctx.Request.Header.Get("token")

		global.Log.Info("打印一下头里的token", zap.Any("token", tokentemp))

		keyResult, err := svc.RedisServiceGet(ctx, tokentemp)
		if err != nil {
			global.Log.Error("redis存储出了点错误", zap.Error(err))
			ctx.JSON(http.StatusInternalServerError, err)
			ctx.Abort()
			return
		}

		global.Log.Info("打印一下token", zap.Any("token", tokentemp), zap.Any("redis key", string(keyResult)))

		jwtConf := utils_jwt.JwtConf{
			AgentUserIdHeader: "agentUserId",
			JwtSecret:         keyResult,
			Issuer:            "joker",
		}
		//token := jwtConf.GetAccessToken(tokentemp)
		Len := len(tokentemp)
		if Len <= 11 || tokentemp == "" {
			ctx.JSON(http.StatusUnauthorized, "Unauthorized")
			ctx.Abort()
			return
		}
		parseToken, err := jwtConf.ParseToken(tokentemp)
		if err != nil {
			global.Log.Error("jwt ctx", zap.Error(err))
			switch err.(*jwt.ValidationError).Errors {
			case jwt.ValidationErrorExpired:
				ctx.JSON(http.StatusUnauthorized, "Unauthorized")
				ctx.Abort()
				return
			case jwt.ValidationErrorIssuer:
				ctx.JSON(http.StatusUnauthorized, "Unauthorized")
				ctx.Abort()
				return
			default:
				ctx.JSON(http.StatusUnauthorized, "Unauthorized")
				ctx.Abort()
				return
			}
		}
		global.Log.Info("parseToken", zap.Any("data", parseToken))
		ctx.Set("uid", parseToken.Uid)
		ctx.Set("zone", parseToken.Zone)
		ctx.Next()
	}
}
